package com.voicechat.firstmet.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.activity.PersonalHomepageActivity;
import com.voicechat.firstmet.activity.PostDetailsActivity;
import com.voicechat.firstmet.adapter.CommunityAdapter;
import com.voicechat.firstmet.base.BaseFragment;
import com.voicechat.firstmet.bean.CommBean;
import com.voicechat.firstmet.bean.CoummunityNotice;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.bean.PostBean;
import com.voicechat.firstmet.client.OssClient;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.imcontrol.MediaUtil;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.CommunityService;
import com.voicechat.firstmet.utils.ConstantSet;
import com.voicechat.firstmet.utils.FileUtils;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.ThreadManager;
import com.voicechat.firstmet.utils.Utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.fragment
 * @ClassName: CommunityHotPostFragment
 * @Description: java类作用描述
 * @Author: ljp
 * @CreateDate: 2019/1/8 15:33
 * @Version: 1.0
 */
public class CommunityNewPostFragment extends BaseFragment {

    @BindView(R.id.recycler_post_hot)
    RecyclerView recyclerPostHot;
    private String token;
    private String deviceInfo;
    private String userId;
    private int page;//页数，用于初见广场分页加载
    public static MySelfInfoBean.ObjectBean mySeleInfo;
    private String TAG = "CommunityNewPostFragment";
    private ArrayList<PostBean.PageBean.ListBean> postLists = new ArrayList<>();
    private CommunityAdapter communityAdapter;
    private Runnable runnable;

    public static CommunityNewPostFragment newInstance() {
        CommunityNewPostFragment fragment = new CommunityNewPostFragment();
        return fragment;
    }
    private LocalBroadcastManager broadcastManager;//刷新广播接收器
    @Override
    protected int loadLayout() {
        return R.layout.fragment_hot_post;
    }
    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this, view);
        page = 1;
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        userId = mySeleInfo.getId();
        initView();
        communityPostList();
    }
    private void initView() {
        communityAdapter = new CommunityAdapter(context, postLists, R.layout.item1_community, "");
        recyclerPostHot.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        recyclerPostHot.setAdapter(communityAdapter);
        communityAdapter.setItemSetClick(new CommunityAdapter.ItemSetClick() {
            @Override
            public void setIconClick(View view, PostBean.PageBean.ListBean listBean) {
                Intent intent = new Intent(context, PersonalHomepageActivity.class);
                intent.putExtra("anchorId", listBean.getUserId());
                context.startActivity(intent);
            }
            @Override
            public void setIconClick(View view, CommBean.MapBean.DynamicBean dynamic) {
                Intent intent = new Intent(context, PersonalHomepageActivity.class);
                intent.putExtra("anchorId", dynamic.getUserId());
                context.startActivity(intent);
            }
            @Override
            public void setItemClick(View view, PostBean.PageBean.ListBean listBean) {
                Intent intent = new Intent(context, PostDetailsActivity.class);
                intent.putExtra("listBean", listBean);
                startActivity(intent);
            }
            @Override
            public void setLikeClick(View view, CommBean.MapBean.DynamicBean dynamic) {
                CommunityService.postLikeAndUnLike(token, deviceInfo, dynamic.getHotId(),
                        CommunityService.LIKE_TYPE.LIKE_POST_TYPE, userId).subscribe(result -> {
                    if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                        if (!TextUtils.isEmpty(dynamic.getIsFabulous()) && dynamic.getIsFabulous().equals("0")) {// 1 已经点赞   0 未点赞
                            dynamic.setIsFabulous("1");
                            dynamic.setFabulousCount(dynamic.getFabulousCount() + 1);
                        } else if (!TextUtils.isEmpty(dynamic.getIsFabulous()) && dynamic.getIsFabulous().equals("1")) {
                            dynamic.setIsFabulous("0");
                            dynamic.setFabulousCount(dynamic.getFabulousCount() - 1);
                        }
                        communityAdapter.notifyDataSetChanged();
                    } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                        Utils.setToken(context);
                    } else {
                        toast_MakeText(result.getMsg());
                    }
                }, throwable -> {
                    Log.i(TAG, "setLikeClick: -------" + throwable.toString());
                });
            }

            @Override
            public void setLikeClick(View view, PostBean.PageBean.ListBean listBean) {
                CommunityService.postLikeAndUnLike(token, deviceInfo, listBean.getId(),
                        CommunityService.LIKE_TYPE.LIKE_POST_TYPE, userId).subscribe(result -> {
                    if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                        if (listBean.getIsFabulous().equals("0")) {//0未点赞 1 点赞
                            listBean.setIsFabulous("1");
                            listBean.setFabulousCount(listBean.getFabulousCount() + 1);
                        } else if (listBean.getIsFabulous().equals("1")) {
                            listBean.setIsFabulous("0");
                            listBean.setFabulousCount(listBean.getFabulousCount() - 1);
                        }
                        communityAdapter.notifyDataSetChanged();
                    } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                        Utils.setToken(context);
                    } else {
                        toast_MakeText(result.getMsg());
                    }
                    // Log.i(TAG, "setLikeClick: -------"+result.toString());
                }, throwable -> {
                    // Log.i(TAG, "setLikeClick: -------"+throwable.toString());
                });
            }

            @Override
            public void setItemClick(View view, CommBean.MapBean.DynamicBean dynamic) {

            }

            @Override
            public void setNoticeClick(View view, List<CoummunityNotice.PageBean.ListBean> notices) {

            }

            @Override
            public void setPlayVoiceClick(PostBean.PageBean.ListBean listBean, View view, int position, View viewPlay) {
                String path = ConstantSet.VOICEINTR + ConstantSet.VOICE_POST + Utils.getVoiceName(listBean.getVoiceUrl());
                Log.i(TAG, "onBindViewHolder: -----" + path);
                Log.i(TAG, "setPlayVoiceClick: -----"+FileUtils.isExists(path));
                if (FileUtils.isExists(path)) {
                    try {
                        player(path, (ImageView) view, position,(ImageView)viewPlay);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
            @Override
            public void setPlayVoiceClick(CommBean.MapBean.DynamicBean dynamic, View view, int position) {
            }
            @Override
            public void setItemClickShare(View view, PostBean.PageBean.ListBean listBean) {
                UMWeb web = new UMWeb(HTTPAPI.URL_SHARE+"id="+listBean.getId()+"&userId="+listBean.getUserId());
                String[] list = getResources().getStringArray(R.array.share_title);
                Random random = new Random();
                web.setTitle(list[random.nextInt(list.length)]);//标题
                if (!TextUtils.isEmpty(listBean.getUrl())) {
                    String[] strings = Utils.spitPictureUrl(listBean.getUrl());
                    web.setThumb(new UMImage(activity, OssConfig.OSS_HTTP+strings[0]));  //缩略图
                }
                web.setDescription(listBean.getContent());//描述
                new ShareAction(activity).withMedia(web)
                        .setDisplayList(SHARE_MEDIA.QQ,SHARE_MEDIA.WEIXIN,SHARE_MEDIA.QZONE,SHARE_MEDIA.WEIXIN_CIRCLE)
                        .setCallback(new UMShareListener() {
                            @Override
                            public void onStart(SHARE_MEDIA share_media) {
                            }
                            @Override
                            public void onResult(SHARE_MEDIA share_media) {
                                Toast.makeText(activity,getResources().getString(R.string.share_success),Toast.LENGTH_LONG).show();
                            }
                            @Override
                            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                                Toast.makeText(activity,getResources().getString(R.string.share_fial),Toast.LENGTH_LONG).show();
                            }
                            @Override
                            public void onCancel(SHARE_MEDIA share_media) {
                                Toast.makeText(activity,getResources().getString(R.string.share_cacal),Toast.LENGTH_LONG).show();
                            }
                        }).open();
            }
        });
    }
    /**
     * 注册广播接收器
     */
    private void registerReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("post");
        broadcastManager.registerReceiver(mAdDownLoadReceiver, intentFilter);
    }
    /**
     * @method
     * @description 广播接收器
     * @date: 2019/1/10 17:36
     * @author: ljp
     * @return
     */
    private BroadcastReceiver mAdDownLoadReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String change = intent.getStringExtra("change");
            if ("Refresh".equals(change)) {
                page = 1;
                communityPostList();
            }else {
                page ++;
                communityPostList();
            }
        }
    };
    /**
     * 注册广播
     */
    @Override
    public void onStart() {
        super.onStart();
        registerReceiver();
    }
    /**
     * 注销广播
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        broadcastManager.unregisterReceiver(mAdDownLoadReceiver);
    }

    /**
     * 注销广播
     */
    @Override
    public void onDetach() {
        super.onDetach();
        broadcastManager.unregisterReceiver(mAdDownLoadReceiver);
    }
    @Override
    public void onResume() {
        super.onResume();
        communityPostList();
    }
    /**
     * @return
     * @method
     * @description 请求帖子信息
     * @date: 2018/10/9 13:52
     * @author: ljp
     */
    private void communityPostList() {
        CommunityService.postNewAndHot(token, deviceInfo, page + "", userId,1).subscribe(postBean -> {
            if (postBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                int i = postBean.getPage().getCount() / postBean.getPage().getPageSize() +
                        (postBean.getPage().getCount() % postBean.getPage().getPageSize() == 0 ? 0 : 1);
                if (page > i) {//判断是否是最后一页{//判断是否是最后一页
                    ((CommunityNewFragment) getParentFragment()).setSmartLoad("");
                } else {
                    if (page == 1) {
                        postLists.clear();
                        postLists.addAll(postBean.getPage().getList());
                        communityAdapter.notifyDataSetChanged();
                        ((CommunityNewFragment) getParentFragment()).setSmartRefresh();
                    }else {
                        postLists.addAll(postBean.getPage().getList());
                        communityAdapter.notifyDataSetChanged();
                        ((CommunityNewFragment) getParentFragment()).setSmartLoad("more");
                    }
                    setThreadPost(postBean.getPage().getList());
                }
            } else if (postBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(postBean.getMsg());
            }
        }, throwable -> {

        });
    }
    /**
     * @return
     * @method
     * @description 启动线程池下载语音信息
     * @date: 2018/10/16 14:30
     * @author: ljp
     */
    private void setThreadPost(List<PostBean.PageBean.ListBean> postBeans) {
        ThreadManager.getThreadPool().execute(runnable = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < postBeans.size(); i++) {
                    if (!TextUtils.isEmpty(postBeans.get(i).getVoiceUrl())) {
                        String voiceInfo = postBeans.get(i).getVoiceUrl();
                        int finalI = i;
                        OssClient.getInstance().init(context).fileDownload(voiceInfo, new OssClient.OnDownloadFile() {
                            @Override
                            public void onDownFileSuccess(InputStream inputStream) {
                                String voiceName = Utils.getVoiceName(postBeans.get(finalI).getVoiceUrl());
                                //Log.i(TAG, "onDownFileSuccess: ---------"+voiceName);
                                String path = ConstantSet.VOICEINTR;
                                try {
                                    OssConfig.writeToLocalPost(path, inputStream, voiceName);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onDownFileProgress(String progress) {
                                //Log.i(TAG, "onDownFileProgress: ----------"+progress);
                            }
                        });
                    }
                }
            }
        });
    }
    int mFirstVoicePlayItem;//第一级列表的喇叭动画初始位置
    int mSecondVoicePlayItem;//第二级列表的喇叭动画初始位置
    //int position;//当前列表的位置
    AnimationDrawable animationDrawable;
    ImageView imageViewIconVoice;
    ImageView imagePlay;
    /**
     * @return
     * @method
     * @description 播放语音
     * @date: 2018/9/28 18:57
     * @author: ljp
     */
    private void player(String path, ImageView imageView, int position,ImageView imagePlay) throws FileNotFoundException {
        imageViewIconVoice = imageView;
        this.imagePlay = imagePlay;
        if (TextUtils.isEmpty(path)) {
            return;
        }
        mSecondVoicePlayItem = -1;
        if (animationDrawable != null) {
            imagePlay.setImageResource(R.mipmap.post_pause);
            MediaUtil.getInstance().stop();
            animationDrawable.stop();
            animationDrawable.selectDrawable(2);
            animationDrawable = null;
            if (mFirstVoicePlayItem != position) {
                mFirstVoicePlayItem = position;
                imageView.setImageResource(R.drawable.post_voice);
                animationDrawable = (AnimationDrawable) imageView.getDrawable();
                animationDrawable.start();
                MediaUtil.getInstance().play(new FileInputStream(path));
                imagePlay.setImageResource(R.mipmap.post_play);
            }
        } else {
            mFirstVoicePlayItem = position;
            imageView.setImageResource(R.drawable.post_voice);
            animationDrawable = (AnimationDrawable) imageView.getDrawable();
            animationDrawable.start();
            MediaUtil.getInstance().play(new FileInputStream(path));
            imagePlay.setImageResource(R.mipmap.post_play);
        }
        MediaUtil.getInstance().setEventListener(new MediaUtil.EventListener() {
            @Override
            public void onStop() {
                imagePlay.setImageResource(R.mipmap.post_pause);
            }
        });
        MediaUtil.getInstance().getPlayer().setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.stop();
                imagePlay.setImageResource(R.mipmap.post_pause);
                if (animationDrawable != null) {
                    animationDrawable.stop();
                    animationDrawable.selectDrawable(2);
                    animationDrawable = null;
                }
            }
        });
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(context).onActivityResult(requestCode, resultCode, data);
    }
}
